<?php

namespace api\mobile;

use app\common\model\Mobile;
use think\facade\Db;

/**
 * 36鲸[这家没跑了]
 *
 * https://erp.36duojing.com/index
 */
class Duojing36 extends BaseModel
{
    private $header = [
        'Content-Type: application/x-www-form-urlencoded',
    ];

    /**
     * 创建订单.
     *
     * @params
     * sub_order_id 系统订单号
     * amount 充值金额
     * mobile 充值号码
     */
    public function create($order)
    {
        $url = $this->info['url'] . '/v1/mobile/order';
        $params = [
            'appKey' => $this->info['app_id'],
            'orderId' => $order['sub_order_id'],
            'mobile' => $order['mobile'],
            'amount' => number_format(fen2yuan($order['amount']), 2),
            'notifyUrl' => $this->notifyUrl,
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, http_build_query($params), $this->header, 5, true);
        $res = json_decode($res, true);

        $supplier_order_no = '';
        $returnCode = $res['return_code'] ?? 500;
        $remark = $res['return_msg'] ?? '';
        switch ($returnCode) {
            case 0: // 下单成功
            case 11004: // 平台订单号重复，也算成功
//                $supplier_order_no = $res['data']['number'];
                $status = self::SUCCESS;
                break;
            case 3001:  // 账户余额不足
                $status = self::LACK_OF_MONEY;
                break;
            case 500:   // 系统错误
                $status = self::NEED_RETRY;
                break;
            case 1001:  // 平台标识码传空
            case 1002:  // 标识码错误
            case 2001:  // 签名传空
            case 2002:  // 签名不正确
            case 11001: // 手机号传空
            case 11002: // 手机号不正确
            case 11003: // 平台订单号传空
            case 11005: // 充值额度传空
            case 11006: // 充值额度格式不正确
            case 11007: // 回调地址传空
            case 11008: // 下单失败
                $status = self::FAIL;
                break;
            default: // 未知错误，需要人工确认
                $status = self::NEED_CONFIRM;
                break;
        }

        return compact('status', 'supplier_order_no', 'remark');
    }

    /**
     * 查询余额.
     *
     * 单位：分
     */
    public function queryAmount()
    {
        $url = $this->info['url'] . '/v1/account/query';
        $params = [
            'appKey' => $this->info['app_id'],
            'time' => date('Y-m-d H:i:s'),
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, http_build_query($params), $this->header);
        $res = json_decode($res, true);
        if (!isset($res['data']['surplus'])) {
            $this->error = $res['return_msg'] ?? '查询频繁';

            return false;
        }

        return yuan2fen($res['data']['surplus']);
    }

    /**
     * 订单查询.
     */
    public function query($orderId)
    {
        $url = $this->info['url'] . '/v1/mobile/status';
        $params = [
            'appKey' => $this->info['app_id'],
            'time' => date('Y-m-d H:i:s'),
            'type' => 0
        ];
        $params['sign'] = $this->getSign($params);
        $res = curlPost($url, http_build_query($params), $this->header);
        $res = json_decode($res, true);

        return $res;
    }

    /**
     * 生成签名.
     */
    public function getSign($params)
    {
        if (isset($params['sign'])) {
            unset($params['sign']);
        }
        ksort($params);
        $str = '';
        foreach ($params as $k => $v) {
            if (!empty($v)) {
                $str .= $k . '=' . $v . '&';
            }
        }
        $str .= 'key=' . $this->info['app_secret'];

        return strtoupper(md5($str));
    }

    /**
     * 订单回调.
     */
    public function notify($params)
    {
        $insert = [
            'sub_order_id' => $params['orderId'] ?? '',
            'params' => json_encode($params, JSON_UNESCAPED_UNICODE),
            'result' => 'SUCCESS',
        ];

        $sign = $params['sign'] ?? '';
        $checkSign = $this->getSign($params);
        if ($sign !== $checkSign) {
            $insert['result'] = '验签失败';
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        $order = Db::name('mobile_order')
            ->where('sub_order_id', $params['orderId'])
            ->where('mobile_supplier_id', $this->info['id'])
            ->find();
        if (empty($order)) {
            $insert['result'] = '订单不存在';
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        if (in_array($order['supplier_status'], [3, 4, 99])) {
            // if ($order['supplier_status'] == 3 || $order['supplier_status'] == 4) {
            $insert['result'] = '已经成功过';
            Db::name('mobile_notify')->insert($insert);

            return 'SUCCESS';
        }

        if ($order['supplier_status'] != 2) {
            $insert['result'] = '订单状态有误：' . $order['supplier_status'];
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        // 供应商订单状态：1订单未创建 2订单已创建 3充值成功 4充值失败
        // 0表示充值中; 1表示已充值; 2表示充值失败;
        $state = strtoupper($params['status']);
        $supplierStatusMap = [
            'SUCCESS' => 3, // 1已充值 --> 3充值成功
            // 2 => 4, // 2充值失败 --> 4充值失败
            'FAIL' => 99, // 2充值失败 --> 充值失败，等待重试
        ];
        $supplierStatus = $supplierStatusMap[$state] ?? 2;
        if ($order['supplier_status'] == $supplierStatus) {
            Db::name('mobile_notify')->insert($insert);

            return 'SUCCESS';
        }
        $update = [
            'supplier_order_no' => $params['number'],
            'supplier_status' => $supplierStatus,
            // 'official_sn' => $params['official_sn'] ?? '',  // 官方流水号
        ];
        $order['official_sn'] = '';
        if ($supplierStatus == 99) {
            $order['notify_url'] = '';  // 失败通知先不发
        } else {
            $update['finish_time'] = time();
        }

        Db::name('mobile_notify')->insert($insert);

        Db::startTrans();
        try {
            // 如果是返佣模式，将订单结算方式改成待结算
            if ($supplierStatus == 3 && $order['settle_type'] == SETTLE_TYPE_PROFIT) {
                if ($order['profit'] == 0) {
                    $update['settle_status'] = 3;
                } elseif ($order['settle_status'] == 1) {
                    $update['settle_status'] = 2;
                }
            }

            Mobile::handleNotify($order, $update);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            $insert['result'] = '订单更新失败' . $order['id'] . '。' . $e->getMessage();
            Db::name('mobile_notify')->insert($insert);

            return $insert['result'];
        }

        return 'SUCCESS';
    }
}
